﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using UDS.Components;
using UDS.Entity;

namespace UDS.SubModule.UnitiveDocument.DocumentFlowPages
{
    /// <summary>
    /// Query 的摘要说明。
    /// </summary>
    public partial class QueryPage : Page
    {
        protected override void OnInit(EventArgs e)
        {
            ddlFlow.SelectedIndexChanged += ddlFlow_SelectedIndexChanged;
            cmdAdd.Click += cmdAdd_Click;
            cmdDelete.Click += cmdDelete_Click;
            cmdQuery.Click += cmdQuery_Click;
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                FillFlow(ddlFlow);
            }

            base.OnLoad(e);
        }

        private void FillFlow(DropDownList ddl)
        {
            ddl.DataSource = Flow.GetAllFlows();
            ddl.DataTextField = "Name";
            ddl.DataValueField = "ID";
            ddl.DataBind();

            if (ddl.Items.Count > 0)
            {
                FillDisplayColumn();
            }
        }

        private void FillFieldName(CheckBoxList cblField, int iFlowID)
        {
            var list = FlowStyleDescription.GetStyleDescriptionByFlow(iFlowID);

            cblField.Items.Clear();
            foreach (var item in list)
            {
                cblField.Items.Add(new ListItem(item.Description, item.Name));
            }
            cblField.Items.Add(new ListItem("流程名", "Flow_Name"));
            cblField.Items.Add(new ListItem("拟稿日期", "Doc_Added_Date"));
            cblField.Items.Add(new ListItem("撰搞人", "RealName"));

            for (int i = 0; i < cblField.Items.Count; i++)
            {
                cblField.Items[i].Selected = true;
            }
        }

        private void FillFieldName(DropDownList ddl, int iFlowID)
        {
            var list = FlowStyleDescription.GetStyleDescriptionByFlow(iFlowID);
            ddl.Items.Clear();
            foreach (var item in list)
            {
                ddl.Items.Add(new ListItem(item.Description, (item.Judged ? "1" : "0") + item.Name));
            }

            ddl.Items.Add(new ListItem("拟稿日期", "2Doc_Added_Date"));
            ddl.Items.Add(new ListItem("拟稿人", "0realname"));
        }

        private void FillStatisticFieldName(DropDownList ddl, int iFlowID)
        {
            var list = FlowStyleDescription.GetStyleDescriptionByFlow(iFlowID, true);
            ddl.Items.Clear();
            foreach (var item in list)
            {
                ddl.Items.Add(new ListItem(item.Description, (item.Judged ? "1" : "0") + item.Name));
            }
        }

        private void FillDisplayColumn()
        {
            FillFieldName(cblDisplay, Int32.Parse(ddlFlow.Items[ddlFlow.SelectedIndex].Value));
            FillFieldName(ddlCondition, Int32.Parse(ddlFlow.Items[ddlFlow.SelectedIndex].Value));

            FillStatisticFieldName(ddlStatistic, Int32.Parse(ddlFlow.Items[ddlFlow.SelectedIndex].Value));
            lbCondition.Items.Clear();
        }

        private void ddlFlow_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillDisplayColumn();
        }

        private void cmdQuery_Click(object sender, EventArgs e)
        {
            string strDisplayColumn = "Doc_ID,Doc_Builder_ID,Flow_ID as flow_id,Step_ID";
            string strCondition = "Flow_ID = " + ddlFlow.SelectedItem.Value;

            for (int i = 0; i < cblDisplay.Items.Count; i++)
            {
                if (cblDisplay.Items[i].Selected)
                {
                    strDisplayColumn = strDisplayColumn + "," + cblDisplay.Items[i].Value + " AS " + cblDisplay.Items[i].Text;
                }
            }

            for (int j = 0; j < lbCondition.Items.Count; j++)
            {
                strCondition = strCondition + " And " + lbCondition.Items[j].Value;
            }

            //			Response.Write("<script language='javascript'>alert('" + strDisplayColumn + "');</script>");

            var db = new Database();
            int iRow = 0;

            SqlParameter[] parameters = {
                Database.MakeInParam("@SelectColumns", SqlDbType.NVarChar, 3000, strDisplayColumn),
                Database.MakeInParam("@Conditions", SqlDbType.NVarChar, 3000, strCondition),
                Database.MakeInParam("@FlowID", SqlDbType.Int, 4, Int32.Parse(ddlFlow.SelectedItem.Value))
            };
            tabResult.Rows.Clear();

            using (SqlDataReader dr = db.RunDataReader("dbo.sproc_Flow_GetDefineQueryDocument", parameters))
            {
                if (dr.FieldCount >= 6)
                {
                    do
                    {
                        var tr = new TableRow();
                        AddRow(tr, dr, iRow == 0 ? true : false);
                        tabResult.Rows.Add(tr);
                        tr.BorderWidth = 1;
                        iRow = iRow + 1;
                    }
                    while (dr.Read());
                }
                if (ddlStatistic.SelectedIndex >= 0)
                {
                    AddStatistic(tabResult, dr.FieldCount - 4, ddlStatistic.SelectedItem.Value.Substring(1), ddlStatistic.SelectedItem.Text, strCondition, Int32.Parse(ddlFlow.SelectedItem.Value));
                }
                dr.Close();
            }
        }

        private void AddStatistic(Table tab, int ColumnSpan, string StatisticField, string StatisticName, string Condition, long FlowID)
        {
            var db = new Database();

            SqlParameter[] parameters = {
                Database.MakeInParam("@SelectColumns", SqlDbType.NVarChar, 3000, "SUM(CONVERT(INT," + StatisticField + ")) AS " + StatisticField),
                Database.MakeInParam("@Conditions", SqlDbType.NVarChar, 3000, Condition),
                Database.MakeInParam("@FlowID", SqlDbType.Int, 4, FlowID)
            };
            using (SqlDataReader dr = db.RunDataReader("dbo.sproc_Flow_GetDefineQueryDocument", parameters))
            {
                if (dr.Read())
                {
                    AddRow(tab, ColumnSpan, StatisticName + "总计:" + dr[StatisticField]);
                }
            }
        }

        private void AddRow(TableRow tr, SqlDataReader dr, bool bCaption)
        {
            for (int i = 4; i < dr.FieldCount; i++)
            {
                var tc = new TableCell();
                if (bCaption == false)
                {
                    tc.Text = dr.GetValue(i).ToString();
                }
                else
                {
                    tc.Text = dr.GetName(i);
                    tc.BackColor = Color.FromArgb(0xf8, 0xf8, 0xf8);
                }
                tr.Controls.Add(tc);
            }
        }

        private void AddRow(Table tab, int ColumSpan, string Caption)
        {
            var tr = new TableRow();

            var tc = new TableCell();
            tc.Text = Caption;
            tc.ColumnSpan = ColumSpan;
            tc.BackColor = Color.FromArgb(0xf8, 0xf8, 0xf8);
            tr.BorderWidth = 1;
            tr.Controls.Add(tc);
            tab.Controls.Add(tr);
        }

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            if (lbCondition.SelectedIndex >= 0)
            {
                lbCondition.Items.Remove(lbCondition.SelectedItem);
            }
        }

        private void cmdAdd_Click(object sender, EventArgs e)
        {
            string ListText;
            string ListValue;
            if (ddlCondition.SelectedIndex >= 0)
            {
                switch (ddlCondition.SelectedItem.Value.Substring(0, 1))
                {
                    case "0":
                        ListText = ddlCondition.SelectedItem.Text + ddlCompare.SelectedItem.Text + txtValue.Text;
                        if (ddlCompare.SelectedIndex != 6)
                        {
                            ListValue = ddlCondition.SelectedItem.Value.Substring(1) + ddlCompare.SelectedItem.Value + "'" + txtValue.Text + "'";
                        }
                        else
                        {
                            ListValue = ddlCondition.SelectedItem.Value.Substring(1) + ddlCompare.SelectedItem.Value + "'%" + txtValue.Text + "%'";
                        }
                        lbCondition.Items.Add(new ListItem(ListText, ListValue));
                        break;
                    case "1":
                        if (ddlCompare.SelectedIndex != 6)
                        {
                            try
                            {
                                Int32.Parse(txtValue.Text);
                                ListText = ddlCondition.SelectedItem.Text + ddlCompare.SelectedItem.Text + txtValue.Text;
                                ListValue = " IsNumeric(" + ddlCondition.SelectedItem.Value.Substring(1) + ")>0 and " + ddlCondition.SelectedItem.Value.Substring(1) + ddlCompare.SelectedItem.Value + txtValue.Text;
                                lbCondition.Items.Add(new ListItem(ListText, ListValue));
                            }
                            catch
                            {
                                Response.Write("<script language='javascript'>alert('请输入数字！');</script>");
                            }
                        }
                        else
                        {
                            Response.Write("<script language='javascript'>alert('不能用此参数！');</script>");
                        }
                        break;
                    case "2":
                        try
                        {
                            DateTime.Parse(txtValue.Text);
                            ListText = ddlCondition.SelectedItem.Text + ddlCompare.SelectedItem.Text + txtValue.Text;
                            ListValue = ddlCondition.SelectedItem.Value.Substring(1) + ddlCompare.SelectedItem.Value + "'" + txtValue.Text + "'";
                            lbCondition.Items.Add(new ListItem(ListText, ListValue));
                        }
                        catch
                        {
                            Response.Write("<script language='javascript'>alert('请输入正确的日期！');</script>");
                            //UDS.Components.Logger.Log(ex.ToString());
                        }
                        break;
                    case "3":
                        break;
                }
            }
        }
    }
}